from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.routers import pdf, image, audio, video, tools
from app.config import settings
import logging
from pathlib import Path

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(
    title="PDF Toolkit API",
    description="PDF工具集API文档",
    version="1.0.0"
)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:8001"],  # 允许前端域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册路由
app.include_router(pdf.router, prefix="/pdf", tags=["PDF处理"])
app.include_router(image.router, prefix="/image", tags=["图片处理"])
app.include_router(audio.router, prefix="/api/audio", tags=["音频处理"])
app.include_router(video.router, prefix="/video", tags=["视频处理"])
app.include_router(tools.router, prefix="/tools", tags=["工具"])

# 启动事件
@app.on_event("startup")
async def startup_event():
    # 确保临时文件目录存在
    temp_dir = Path("temp")
    temp_dir.mkdir(exist_ok=True)
    logger.info("服务启动成功")

# 关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    # 清理临时文件
    import shutil
    temp_dir = Path("temp")
    if temp_dir.exists():
        shutil.rmtree(temp_dir)
    logger.info("服务关闭")

@app.get("/health")
async def health_check():
    """健康检查接口"""
    return {"status": "healthy"}

@app.get("/version")
async def version():
    """获取API版本信息"""
    return {
        "version": "1.0.0",
        "name": settings.PROJECT_NAME
    }

@app.middleware("http")
async def log_requests(request, call_next):
    logger.info(f"Request: {request.method} {request.url}")
    response = await call_next(request)
    logger.info(f"Response: {response.status_code}")
    return response 